package com.jiaquyun.jcyx.jetpack.mode

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.jiaquyun.jcyx.app.JCApplication
import com.jiaquyun.jcyx.jetpack.api.GoodsRepository
import com.jiaquyun.jcyx.entity.*
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.HttpResponseData
import com.module.lemlin.http.SubscribeViewModel

class GoodsViewModel(application: Application) : CartViewModel(application) {

    private val mGoodsRepository = GoodsRepository()

    val goodsListLiveData = MutableLiveData<HttpResponseBody<GoodsListResponse>>()
    val goodsActiveLiveData = MutableLiveData<HttpResponseBody<GoodsActiveResponse>>()
    val cateListLiveData = MutableLiveData<HttpResponseBody<CatResponse>>()

    val searchLiveData = MutableLiveData<String>()


    val mGoodsRequest: GoodsRequest = GoodsRequest(shop_id = "${JCApplication.userShops?.id?:"55"}")

    fun goodsCategoryList(pid: Int = 0) {
        setRxLifeScope(SubscribeViewModel(cateListLiveData)) {
            mGoodsRepository.goodsCategoryList(pid.toString())
        }
    }

    fun goodsActivity(id: Int) {
        setRxLifeScope(SubscribeViewModel(goodsActiveLiveData)) {
            mGoodsRepository.goodsActivity(id.toString())
        }
    }

    fun goodsList(isLoadMore: Boolean = false) {
        val listener = object : SubscribeViewModel<GoodsListResponse>(goodsListLiveData) {
            override fun onSuccess(resp: GoodsListResponse) {
                super.onSuccess(resp.apply { loadMore = mGoodsRequest.page > 1 })
                mGoodsRequest.page += 1
            }
        }
        if (!isLoadMore)
            mGoodsRequest.page = 1
        setRxLifeScope(listener) {
            mGoodsRepository.goodsList(mGoodsRequest)
        }
    }

    val goodsDetailsLiveData = MutableLiveData<HttpResponseBody<GoodsDetailsResponse>>()
    fun goodsInfo(id: Int) {
        setRxLifeScope(SubscribeViewModel(goodsDetailsLiveData)) {
            mGoodsRepository.goodsInfo(id.toString())
        }
    }

    var isCollect: Boolean = false
    val goodsCollectLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun goodsCollect(goodsId: Int, type: Int = 0) {
        setRxLifeScope(object : SubscribeViewModel<HttpResponseData>(goodsCollectLiveData) {
            override fun onSuccess(resp: HttpResponseData) {
                isCollect = !isCollect
                super.onSuccess(resp)
            }
        }) {
            mGoodsRepository.goodsCollect(goodsId.toString(),type.toString())
        }
    }
}